<?php
/**
 * Description: 获取当天的上岸计划
 * User: devforma
 * Date: 15/1/7
 * Time: 09:59
 */

require __DIR__ . '/includes/utils.php';

class GetLatestPlan implements iController {

    private $missionMeta, $blockedNotes;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        //任务配置信息
        $this->missionMeta = DailyPlanUtils::getMissionMeta();

        //学习天数
        $learnedDays = 0;

        //需要屏蔽的知识点
        $this->blockedNotes = [959, 1512, 537];

        /**-----------------------------------------------------------------
         | 获取任务数据
        ------------------------------------------------------------------*/
        if (validateUser($queryArgs) !== 1) { //非注册用户
            //取国考默认任务
            $originalMissionData = DailyPlanUtils::getDefaultMissionData(1126, 0);

        } elseif ($userData = DailyPlanUtils::getUserData($queryArgs['user_id'])) { //注册用户

            //获取当天任务
            $originalMissionData = DailyPlanUtils::getCurrentMissions($queryArgs['user_id']);

            //如果无当天任务,取所选考试项目默认任务
            if (empty($originalMissionData)) {
                $originalMissionData = DailyPlanUtils::getDefaultMissionData($userData->testarea_id, $queryArgs['user_id']);
            }

            //计算已经学习的天数
            $learnedDays = ceil((time() - strtotime($userData->create_time))/(24*60*60));

        } else {
            return genOutput(1000);
        }

        return genOutput(1, [
            'plan' => $this->getTodayPlan($queryArgs['user_id'], $originalMissionData),
            'learned_days' => $learnedDays
        ]);
    }


    /**
     * 根据分组任务列表和额外任务列表生成今日任务
     *
     * @param int $userId 用户id
     * @param array $originalMissionData 原始任务列表
     * @return array
     */
    private function getTodayPlan($userId, $originalMissionData) {
        $missionList = [];

        //获取分组任务列表和额外任务列表
        list($groupedMissions, $extraMissions) = $this->groupMissions($originalMissionData);

        //开启计划任务
        if (!empty($userId)) {
            if (!empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_BEGINNER])) {
                $missionList[] = ['items' => $groupedMissions[DailyPlanUtils::MISSIONTYPE_BEGINNER]];
            } elseif ($examIntroMissionData = $this->getExamIntroTask($userId)) {
                $missionList[] = $examIntroMissionData;
            }
        }

        //取第一个知识点任务
        if (!empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING])) {
            $missionList[] = ['items' => array_shift($groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING])];
        }

        //取时政热点任务
        if (!empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_CURRENTAFFAIR])) {
            $missionList[] = ['items' => $groupedMissions[DailyPlanUtils::MISSIONTYPE_CURRENTAFFAIR]];
        }

        //取剩下知识点任务
        if (!empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING])) {
            foreach ($groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING] as $mission) {
                $missionList[] =  ['items' => $mission];
            }
        }

        //取测验任务
        if (!empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_TEST])) {
            $missionList[] = ['items' => $groupedMissions[DailyPlanUtils::MISSIONTYPE_TEST]];
        }

        //计算基础任务数量
        $basicCount = count($missionList);

        //取额外任务
        if (!empty($extraMissions)) {
            $missionList = array_merge($missionList, $extraMissions);
        }

        return [
            'date' => date('Y-m-d'),
            'basic_count' => $basicCount,
            'tasks' => $missionList
        ];
    }


    /**
     * 对原始任务列表进行分组、提取额外任务
     *
     * @param array $originalMissionData
     * @return array
     */
    private function groupMissions(&$originalMissionData) {
        //根据任务类型分组
        $groupedMissions = [
            DailyPlanUtils::MISSIONTYPE_BEGINNER        => [], //开启计划任务
            DailyPlanUtils::MISSIONTYPE_NOTELEARNING    => [], //知识点学习和复习任务合并到该组
            DailyPlanUtils::MISSIONTYPE_CURRENTAFFAIR   => [], //时政热点任务
            DailyPlanUtils::MISSIONTYPE_TEST            => []  //小测验和周测验任务合并到该组
        ];

        //自主抽取的额外任务
        $extraMissions = [];

        $availableNotes = getNewNoteHierarchy();
        foreach ($originalMissionData as $missionData) {
            //构造任务数据
            $mission = [
                'task_id'    => (int)$missionData->id,
                'title'      => $missionData->mission_title,
                'subtitle'   => '',
                'content_id' => (int)$missionData->mission_content_id,
                'content'    => $missionData->mission_type == DailyPlanUtils::MISSIONTYPE_BEGINNER ? $missionData->mission_content : '',
                'intro'      => $this->missionMeta[$missionData->mission_type]->remark,
                'done'       => $missionData->action_type == 1,
                'type'       => $this->missionMeta[$missionData->mission_type]->type_name
            ];

            //知识点任务特殊处理
            if ($missionData->mission_type == DailyPlanUtils::MISSIONTYPE_NOTELEARNING || $missionData->mission_type == DailyPlanUtils::MISSIONTYPE_NOTEREVIEW) {

                //如果知识点不可用,过滤掉
                if (!isset($availableNotes[$missionData->mission_content_id])
                    || in_array($missionData->mission_content_id, $this->blockedNotes)) continue;

                //该知识点任务是额外抽取的任务
                if ($missionData->mission_pair == -1) {
                    $extraMissions[] = ['items' => [$mission]];
                    continue;
                }

                //知识点任务配对
                if (empty($groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING][$missionData->mission_pair])) {
                    $groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING][$missionData->mission_pair] = [$mission];
                } else {
                    $groupedMissions[DailyPlanUtils::MISSIONTYPE_NOTELEARNING][$missionData->mission_pair][] = $mission;
                }

                continue;
            }

            //周测验任务类型处理
            if ($missionData->mission_type == DailyPlanUtils::MISSIONTYPE_WEEKTEST)
                $missionData->mission_type = DailyPlanUtils::MISSIONTYPE_TEST;

            $groupedMissions[$missionData->mission_type][] = $mission;
        }

        return [$groupedMissions, $extraMissions];
    }

    /**
     * 生成考试介绍任务
     * @param int $userId 用户id
     * @return array|false
     */
    private function getExamIntroTask($userId) {
        global $uddb;

        //获取未完成的开启计划任务
        $today = date('Y-m-d 00:00:00');
        $sql = "SELECT * FROM `dp_recent_available_mission` WHERE `user_id`={$userId} AND `mission_status`=0 AND `mission_date`<'{$today}'";
        if ($examIntro = $uddb->getRow($sql)) {

            //开启日期
            $actionDate = date('Y.m.d', strtotime($examIntro->mission_date));

            //构造该任务跳转url
            $params = unserialize($examIntro->mission_content);
            $url = "http://daily.edu.appublisher.com/web/dp/index.php?exam_id={$params['exam_id']}&position={$params['position']}&action_date={$actionDate}";

            $uddb->insert($uddb->recentMissionInfo, [
                'user_id'            => $userId,
                'mission_type'       => DailyPlanUtils::MISSIONTYPE_BEGINNER,
                'mission_title'      => $examIntro->mission_title,
                'mission_content_id' => 0,
                'mission_content'    => $url,
                'action_type'        => 0,
                'mission_pair'       => 0,
                'available'          => 1
            ]);

            //返回数据
            return [
                'items' => [
                    [
                        'task_id' => intval($uddb->lastInsertId()),
                        'title' => $examIntro->mission_title,
                        'subtitle' => '考试介绍',
                        'content_id' => 0,
                        'content' => $url,
                        'intro' => $this->missionMeta[DailyPlanUtils::MISSIONTYPE_BEGINNER]->remark,
                        'type' => '开启计划',
                        'done' => false
                    ]
                ]
            ];
        }

        return false;
    }
}
